package L614;

/**
 * @program: javase
 * @description: 给你一个字符串 s，找到 s 中最长的回文子串。
 * @author: luolidong
 * @create: 2021-06-14 10:11
 * @version: 1.0
 */
public class Demo2 {
    public String longestPalindrome(String s) {
        if(s.length()==1) return s;
//        abcbc
        int maxLen = 0;
        int maxStartIndex = 0;
        int left,right;

        for (int i = 0; i <s.length() ; i++) {
            int len=1;//默认为1
            left=i-1;
            right=i+1;
//            向左比较
            while (left>=0&&s.charAt(left)==s.charAt(i)){
                left--;
                len++;
            }
            //            向右比较
            while (right<s.length()&&s.charAt(right)==s.charAt(i)){
                right++;
                len++;
            }
//            左右比较
            while (left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)){
                left--;
                right++;
                len+=2;//这里是左右两个
            }
            if(len>maxLen){
                maxLen=len;
                maxStartIndex=left;
            }
        }
        return s.substring(maxStartIndex+1, maxStartIndex+maxLen+1);
    }

    public static void main(String[] args) {
        String s = new Demo2().longestPalindrome("abcdcbds");
        System.out.println(s);
    }
}
